package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.exceptionResolver.ExceptionMessage;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    MemberService memberService;
    @Reference
    OrderService orderService;
    @Reference
    ReportService reportService;

    @RequestMapping("/queryCurrentYearMemberCount")
    public Map queryCurrentYearMemberCount() {
        return reportService.queryCurrentYearMemberCount();
    }

    @RequestMapping("/getMemberInTime")
    public Result getMemberInTime(@RequestBody Map map) throws Exception {
        String begin = (String) map.get("beginDate");
        String end = (String) map.get("endDate");
        if (begin!=null&&begin.length()!=0&&end!=null&&end.length()!=0){
            Date beginDate = DateUtils.parseString2Date(begin);
            Date endDate = DateUtils.parseString2Date(end);
            List list = reportService.getMonthlyMemberCount(beginDate,endDate);
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,list);
        }
        return null;
    }


    @RequestMapping("/getMemberReport")
    public Map getMemberReport(Integer year) {
        Map map = memberService.getReport(year);
        return map;
    }

    @RequestMapping("/getSetmealReport")
    @ExceptionMessage(value = MessageConstant.QUERY_SETMEAL_FAIL)
    public Result getSetmealReport() {
            List<Map> SetmealReport = orderService.getSetmealReport();
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, SetmealReport);
    }

    @RequestMapping("/getBusinessReportData")
    @ExceptionMessage(value = "")
    public Result getBusinessReportData(@RequestBody String date) throws ParseException {
        Map map = reportService.getBusinessReportData(date);

        return new Result(true, "", map);
    }

    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response, String date) throws Exception {

        Map businessReport = reportService.getBusinessReportData(date);
        if (businessReport == null) {
            new RuntimeException("数据为空");
        }
        Integer todayNewMember = (Integer) businessReport.get("todayNewMember");
        Integer totalMember = (Integer) businessReport.get("totalMember");
        Integer thisWeekNewMember = (Integer) businessReport.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) businessReport.get("thisMonthNewMember");
        Integer todayOrderNumber = (Integer) businessReport.get("todayOrderNumber");
        Integer todayVisitsNumber = (Integer) businessReport.get("todayVisitsNumber");
        Integer thisWeekOrderNumber = (Integer) businessReport.get("thisWeekOrderNumber");
        Integer thisWeekVisitsNumber = (Integer) businessReport.get("thisWeekVisitsNumber");
        Integer thisMonthOrderNumber = (Integer) businessReport.get("thisMonthOrderNumber");
        Integer thisMonthVisitsNumber = (Integer) businessReport.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal = (List<Map>) businessReport.get("hotSetmeal");
        String reportDate = (String) businessReport.get("reportDate");

        InputStream is = request.getSession().getServletContext().getResourceAsStream("template/report_template.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        XSSFSheet sheet = workbook.getSheetAt(0);

        //设置日期
        sheet.getRow(2).getCell(5).setCellValue(reportDate);

        //设置
        sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
        sheet.getRow(4).getCell(7).setCellValue(totalMember);
        sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
        sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
        sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
        sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
        sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
        sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
        sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
        sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
        int i = 0;
        for (Map map : hotSetmeal) {
            sheet.getRow(12 + i).getCell(4).setCellValue((String) map.get("name"));
            sheet.getRow(12 + i).getCell(5).setCellValue((Long) map.get("setmeal_count"));
            BigDecimal proportion = (BigDecimal) map.get("proportion");
            sheet.getRow(12 + i).getCell(6).setCellValue(proportion.doubleValue());
            i++;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
        workbook.write(response.getOutputStream());
        workbook.close();
        is.close();
    }

    @RequestMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response, String date) throws Exception {
        InputStream is = request.getSession().getServletContext().getResourceAsStream("template/report.jasper");
        Map businessReportData = reportService.getBusinessReportData(date);
        if (businessReportData == null) {
            throw new RuntimeException("数据为空");
        }
        List<Map> hotSetmeal = (List<Map>) businessReportData.get("hotSetmeal");

        JasperPrint print = JasperFillManager.fillReport(is, businessReportData , new JRBeanCollectionDataSource(hotSetmeal));

        response.setContentType("application/pdf");
        response.setHeader("content-Disposition", "attachment;filename=report.pdf");
        JasperExportManager.exportReportToPdfStream(print, response.getOutputStream());
        is.close();
    }

    @RequestMapping("/getMemberSexReport")
    public Result getMemberSexReport(){
        try {
            List<Map> list= memberService.findMemberSex();
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport(){
        try {
            List<Map> list= memberService.findMemberAge();
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
}

